import React, {useEffect, useRef, useState} from 'react';
import {ScrollView, StyleSheet, Text, View} from 'react-native';
import screen from '../../utils/screen';
import TouchableView from '../../components/touchableView';
import {useToast} from '../../components/toast/useToast';
import BleUtil from '../../utils/bleUtil';
import {useLoading} from '../../components/loading/useLoading';
import {useAppStore} from '../../store/useAppStore';
import _ from 'lodash'

const DebugBle = ({data,count,onClose,onCloseDebug})=>{


    const toast = useToast()
    const loading = useLoading()
    const [list,setList] = useState([])


    const timerRef = useRef(null)
    const {appState:{currentDevice,pressure},updateAppState }= useAppStore()

    useEffect(()=>{


        return ()=>{
            timerRef.current && clearInterval(timerRef.current)
        }
    },[])


    const sendCmd = (cmd)=>{
        BleUtil.write(data.id,cmd).then(()=>{
            console.log(cmd);
        }).catch(error=>{
            console.log('write error:',error);
        })
    }

    const sendCmdList = (cmdList,isSync)=>{

        BleUtil.clearResults()
        let promiseList = []
        cmdList.forEach((cmd,index)=>{
            let promise = new Promise((fulfill,reject)=>{
                setTimeout(()=>{
                    BleUtil.writeWithoutResponse(data.id,cmd).then(()=>{
                        console.log(index +' cmd send',);
                        setList(prev=>{
                            let newList = _.clone(prev)
                            newList.push('send cmd:'+ cmd)
                            return newList
                        })
                        fulfill(cmd)
                    }).catch(error=>{
                        reject(error)
                    })
                },2000 * index)
            })
            promiseList.push(promise)
        })
        Promise.all(promiseList).then(values=>{

            timerRef.current && clearInterval(timerRef.current)
            timerRef.current = setInterval(()=>{
                const results = BleUtil.checkResults()
                if(!results.length) return
                const lastResult = results[results.length - 1]
                const findIndex = values.findIndex(it=>{
                    return it.includes(lastResult.cmd)
                })
                if(findIndex > -1){
                    console.log(values[findIndex] + ',' ,lastResult.result);
                    setList(results)
                    if(findIndex == values.length - 1){
                        clearInterval(timerRef.current)


                    }

                }

            },1000)

        }).catch(error=>{

            console.log(error);

        })

    }

    const syncToDevice = ()=>{

        if(!list.length) return
        loading.show('获取中')
        let cmdList = []
        list.forEach((item,index)=>{
            const cmd = item.urgent ?
                `setSOSContact 100 ${item.phone}\r\n`
                : `setContact ${index + 1} ${item.phone}\r\n`
            cmdList.push(cmd)
        })
        sendCmdList(cmdList,true)

    }

    const onSyncClick = ()=>{
        if(!list.length) return

        BleUtil.isPeripheralConnected(data.id).then(isConnected=>{
            console.log('是否连接',isConnected);
            if(isConnected){
                syncToDevice()
            }else{
                toast.show('设备已断开连接,请重新连接')
                updateAppState({
                    currentDevice:null,
                    battery:0
                })

            }
        })
    }

    const onGetMessage = ()=>{
        clearList()
        let cmdList = []
        for (let i = 0; i <= count.tmp; i++) {
            const cmd = `getTemplate ${i}\r\n`
            cmdList.push(cmd)
        }
        sendCmdList(cmdList)
    }

    const onGetContact = ()=>{
        clearList()
        let cmdList = []
        for (let i = 0; i <= count.contact; i++) {
            const cmd = `getContact ${i}\r\n`
            cmdList.push(cmd)
        }

        sendCmdList(cmdList)
    }

    const clearList = ()=>{
        setList([])
    }

    return (
        <View style={styles.container}>

            <ScrollView>

                <TouchableView
                    style={styles.moduleView}
                    onPress={onGetMessage}
                >
                    <Text style={styles.title}>获取短信模板</Text>
                    <Text style={styles.rightText}>-</Text>
                </TouchableView>

                <TouchableView
                    style={styles.moduleView}
                    onPress={onGetContact}
                >
                    <Text style={styles.title}>获取联系人</Text>
                    <Text style={styles.rightText}>-</Text>
                </TouchableView>

                {
                    list && (
                        <View>
                            {
                                list.map((item,index)=>{
                                    return (
                                        <Text key={index.toString()}>{JSON.stringify(item)}</Text>
                                    )
                                })
                            }
                        </View>
                    )
                }


            </ScrollView>


            <TouchableView
                style={styles.moduleView}
                onPress={()=>{
                    setList([])
                }}>
                <Text style={styles.title}>清空列表</Text>
            </TouchableView>
            <TouchableView
                style={styles.moduleView}
                onPress={onCloseDebug}>
                <Text style={styles.title}>关闭调试</Text>
            </TouchableView>
            <TouchableView
                style={styles.moduleView}
                onPress={onClose}>
                <Text style={styles.title}>关闭</Text>
            </TouchableView>
        </View>
    )
}
export default DebugBle

const styles = StyleSheet.create({
    container:{
        flex:1,marginTop: 200,backgroundColor: '#fff'
    },
    moduleView: {
        backgroundColor: '#fff',  height: screen.PIXEL_88,
        paddingHorizontal: screen.PIXEL_30, flexDirection: 'row', alignItems: "center",
        justifyContent: 'space-between',
        borderBottomWidth:0.3,borderBottomColor:'#eee'
    },
    title: {
        color:'#7E8B94',fontSize:13
    },
    rightText:{
        color:'#333',fontSize:13
    },
})
